import React, { useRef, useState, useEffect } from 'react';
import { useTranslation, Trans } from 'react-i18next';
import successIcom from '../assets/images/1747883653204.png'
import { getDynamicFonts } from '@/utils/fontUtils';
import { request } from '@/api/request';

interface ContactUsModalProps {
    show: boolean;
    onClose: () => void;
}

/**
 * 联系我们弹窗组件
 * 功能：允许用户发送反馈邮件，支持多语言，包含成功状态展示
 */
const ContactUsModal: React.FC<ContactUsModalProps> = ({ show, onClose }) => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const textareaRef = useRef<HTMLTextAreaElement>(null);
    const [inputValue, setInputValue] = useState('');
    const [error, setError] = useState(false);
    const [isFocused, setIsFocused] = useState(false);
    const [success, setSuccess] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const userEmail = localStorage.getItem('user_email') || 'your email';

    // 每次打开弹窗时重置为输入框状态
    useEffect(() => {
        if (show) {
            setSuccess(false);
            setInputValue('');
            setError(false);
            setIsLoading(false);
        }
    }, [show]);

    if (!show) return null;

    /**
     * 发送反馈邮件
     * 包含输入验证、API调用、错误处理和状态管理
     */
    const handleSend = async () => {
        // 输入验证：检查内容是否为空
        if (!inputValue.trim()) {
            setError(true);
            if (textareaRef.current) {
                textareaRef.current.focus();
            }
            return;
        }

        // 清除之前的错误状态
        setError(false);
        setIsLoading(true);

        try {
            // 向服务器发起发送邮件的请求
            const res = await request.post('/api/visitor/sendMailToSelf', {
                content: inputValue.trim()
            });

            // console.log('发送邮件响应:', res.data);

            // 检查API响应是否成功
            if (res.data.success === true) {
                // 发送成功，显示成功状态
                setSuccess(true);
            } else {
                // API返回失败，显示错误信息
                setError(true);
                // console.error('发送邮件失败:', res.data.message || '未知错误');
                console.error('send mail failed',res.data.message || 'unknown error');
            }
        } catch (error) {
            // 网络错误或其他异常
            setError(true);
            // console.error('发送邮件异常:', error);
            console.error('send mail failed',error);
        } finally {
            // 无论成功失败都要停止加载状态
            setIsLoading(false);
        }
    };

    // textarea 边框样式
    let textareaBorder = 'border border-neutral-700';
    if (error) {
        textareaBorder = 'border border-red-500';
    } else if (isFocused) {
        textareaBorder = 'border border-blue-500';
    }

    return (
        <>
            {/* 蒙版 */}
            <div
                className="fixed inset-0 z-40 bg-black/50 backdrop-blur-sm min-h-screen w-full modal-backdrop"
                style={{ marginTop: 0 }}
                onClick={onClose}
            ></div>
            {/* 弹窗主体 */}
            <div
                id="contactUs"
                data-modal-backdrop="static"
                tabIndex={-1}
                aria-hidden="true"
                className="fixed top-0 left-0 right-0 z-50 w-full p-4 overflow-x-hidden overflow-y-auto h-[calc(100%-1rem)] max-h-full flex justify-center items-center"
                style={{}}
            >
                <div className="relative max-h-full">
                    <div className="relative rounded-lg shadow-2xs dark:bg-gray-700">
                        <div className="md:w-[396px] max-w-[396px] relative bg-stone-900 rounded-[10px] border border-neutral-700">
                            {success ? (
                                <div style={{ fontFamily: dynamicFonts.font3 }} className="w-full pt-7 px-6 pb-6 gap-6 flex flex-col relative bg-stone-900 rounded-[10px] border border-neutral-700 overflow-hidden">
                                    <div className="flex-col justify-center items-center gap-2 flex">
                                        <img src={successIcom} alt="success" className="w-26 h-24 mx-auto" />
                                        <i
                                            className="fas fa-times absolute top-3 right-3 cursor-pointer text-2xl text-white"
                                            style={{ width: 24, height: 24, lineHeight: '24px', textAlign: 'center' }}
                                            onClick={onClose}
                                            aria-label="Close"
                                        ></i>
                                    </div>
                                    <div className="flex-col justify-center items-center gap-2 flex mt-1">
                                        <div className="flex-col justify-center items-center gap-2 flex">
                                            {/* 标题  */}
                                            <div className="text-white text-[1.5em] text-center font-semibold leading-[34px]">
                                                <Trans i18nKey="contactUs.successTitle" />
                                            </div>
                                            <div className="w-full text-center text-neutral-400 text-sm font-normal leading-tight">{t('contactUs.successDesc', { email: userEmail })}</div>
                                        </div>
                                    </div>
                                </div>
                            ) : (
                                <div style={{ fontFamily: dynamicFonts.font4 }} className="w-full md:h-[354px] h-[340px] p-7 gap-6 flex  flex-col relative bg-stone-900 rounded-[10px] border border-neutral-700 overflow-hidden">
                                    {/* 右上角关闭按钮 */}
                                    <i
                                        className="fas fa-times absolute top-4 right-4 z-10 cursor-pointer text-2xl text-white"
                                        style={{ width: 24, height: 24, lineHeight: '24px', textAlign: 'center' }}
                                        onClick={onClose}
                                        aria-label="Close"
                                    ></i>
                                    <div className="flex flex-col justify-start items-start gap-2 w-full">
                                        {/* 标题  */}
                                        <div className="w-full text-start text-white text-[1.8rem] font-bold leading-[34px] mb-1">{t('contactUs.title')}</div>
                                        {/* 说明  */}
                                        <div style={{ fontFamily: dynamicFonts.font3 }} className="text-neutral-400 text-sm font-medium leading-tight">
                                            {t('contactUs.desc')}
                                        </div>
                                    </div>
                                    <div className="flex flex-col justify-start items-start gap-7 w-full">
                                        <div className="w-full">
                                            <textarea
                                                style={{ fontFamily: dynamicFonts.font2 }}
                                                id="textarea_contact_us_closed_sidebar"
                                                className={`w-full h-[120px] placeholder:text-[rgb(100,107,124)] text-white bg-neutral-800 rounded-[10px] p-[1rem] focus:outline-none ${textareaBorder}`}
                                                placeholder={t('contactUs.placeholder')}
                                                name="contact_us[description]"
                                                ref={textareaRef}
                                                value={inputValue}
                                                onChange={e => { setInputValue(e.target.value); setError(false); }}
                                                onFocus={() => setIsFocused(true)}
                                                onBlur={() => setIsFocused(false)}
                                                disabled={isLoading}
                                            ></textarea>
                                        </div>
                                        <button
                                            type="button"
                                            className={`px-4 py-3 w-full rounded-[10px] border text-white text-sm font-semibold leading-tight items-center justify-center inline-flex focus:outline-none focus:ring-0 active:outline-none active:ring-0 ${
                                                isLoading 
                                                    ? 'bg-gray-500 border-gray-500 cursor-not-allowed' 
                                                    : 'bg-[#E75275] border-[#E75275] hover:border-[#E75275]'
                                            }`}
                                            style={{ boxShadow: 'none' }}
                                            onClick={handleSend}
                                            disabled={isLoading}
                                        >
                                            {isLoading ? t('contactUs.sending') : t('contactUs.send')}
                                        </button>
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </>
    );
};

export default ContactUsModal; 